/**
 * @file PatientsResource.java
 * handles all the CRUD operations for request on several patient resources.
 * 
 * @author Christopher Nostand (chn8sh)
 * @date 21 March 2011	(modified for project)
 *		 03 April 2011	(last updated)
 */
package aperturescience.resources;
import java.io.IOException;

import org.json.JSONException;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;

import aperturescience.types.JSONMessageResponse;
import aperturescience.types.JSONPatient;
import aperturescience.wargames.WarGamesApplication;

/**
 * @class PatientsResource
 * this class defines all the HTTP requests for a set of Patient resource
 *
 *		JSONObject postPatient(Representation entity) creates a Patient resource
 *		Representation toXml() retrieves all Patient resources
 */
/**
 * 
 * Resource that manages a list of patients.
 * 
 */
public class PatientsResource extends ServerResource
{
	@Put("JSON")
	public JsonRepresentation putPatient(Representation entity) {
		return postPatient(entity);
	}
	/**
	 * @method postPatient
	 * Handles POST requests; creates a Patient resource
	 *
	 * @param entity	a representation of the resource to-be-updated
	 * @pre  entity is initialized
	 * @post if the resource exists, all values are replaced with the new values; 
	 * 		 otherwise a new resource is created
	 * @returns a JSON representation of the Patient resource
	 */
	@Post("JSON")
	public JsonRepresentation postPatient(Representation entity) //throws IOException
	{
		JsonRepresentation result = null;
		try {
			JSONPatient patient = new JSONPatient(entity);
			DatabaseResource db = new DatabaseResource(WarGamesApplication.couchdburl, WarGamesApplication.databasename);
			String patientId = db.createPatient(patient);
			if( patientId != null ) {
				result = JSONMessageResponse.generateMessageRep( 201, patientId );
			} else { // Patient is already registered.
				result = JSONMessageResponse.generateMessageRep( 409, "Conflict" );
			}
		}
		catch (IOException e) {
			result = JSONMessageResponse.generateMessageRep("999", e.toString());
			//TODO fix verbose error messages (above and below)
		}
		catch (JSONException e) {
			result = JSONMessageResponse.generateMessageRep("999", e.toString());
		}
		catch (Throwable e) {
			result = JSONMessageResponse.generateMessageRep("999", e.toString());
		}
		return result;
	}

	@Get("JSON")
	public JsonRepresentation toJSON() {
		DatabaseResource db = new DatabaseResource(WarGamesApplication.couchdburl, WarGamesApplication.databasename);
		return new JsonRepresentation(db.getAllPatients());
	}

//TODO remove, this is the client's job. (give to front-end as a template)
//	/**
//	 * @method toXml
//	 * Handles all GET requests; retrieves all Patient resources in the database
//	 *
//	 * @returns a listing of all registered patients
//	 */
//	@Get("xml")
//	public Representation toXml() {
//		// Generate the right representation according to its media type.
//		DatabaseResource db = new DatabaseResource(WarGamesApplication.couchdburl, WarGamesApplication.databasename);
//		JSONArray jobj_array = db.getAllPatients();
//		int length = jobj_array.length();
//		try
//		{
//			DomRepresentation representation = new DomRepresentation(MediaType.TEXT_XML);
//			// Generate a DOM document representing the list of patients.
//			Document d = representation.getDocument();
//			Element r = d.createElement("patients");
//			d.appendChild(r);
//
//			for(int i=0; i < length; i++)
//			{
//				Element eltPatient = d.createElement("patient");
//				JSONObject jobj = jobj_array.getJSONObject(i); //db.getPatient(jobj_array.getJSONObject(i).getString("id"));
//
//				if(jobj.getString(JSONPatient.ID).equals("counter")) continue;
//
//				Element eltId = d.createElement("id");
//				eltId.appendChild(d.createTextNode(jobj.getString(JSONPatient.ID)));
//				eltPatient.appendChild(eltId);                
//
//				Element eltName = d.createElement("name");
//				eltName.appendChild(d.createTextNode(jobj.getString(JSONPatient.NAME)));
//				eltPatient.appendChild(eltName);
//
//				Element eltDescription = d.createElement("description");
//				eltDescription.appendChild(d.createTextNode(jobj.getString(JSONPatient.DESCRIPTION)));
//				eltPatient.appendChild(eltDescription);
//
//				Element eltCadiacState = d.createElement("cardiacstate");
//				eltCadiacState.appendChild(d.createTextNode(jobj.getString("cardiacstate")));
//				eltPatient.appendChild(eltCadiacState);
//
//				Element eltRespiratoryState = d.createElement("respiratorystate");
//				eltRespiratoryState.appendChild(d.createTextNode(jobj.getString("respiratorystate")));
//				eltPatient.appendChild(eltRespiratoryState);
//
//				Element eltMentalState = d.createElement("mentalstate");
//				eltMentalState.appendChild(d.createTextNode(jobj.getString("mentalstate")));
//				eltPatient.appendChild(eltMentalState);
//
//				r.appendChild(eltPatient);
//			}
//			d.normalizeDocument();
//
//			// Returns the XML representation of this document.
//			return representation;
//		} 
//		catch (JSONException e){
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} catch(ResourceException e){
//			e.printStackTrace();
//			//code 409 means document already exists						
//		}
//		return null;
//	}
}